import datetime
import Core.IO as IO
import Core.MongoDB as MongoDB
import Core.Gadget as Gadget
import Core.Algorithm as Algorithm
# import Algorithm
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdate
import Core.Gadget as gadget
import time

def StockList():
    trades = database.find("Instruments", "Stock")
    for trade in trades:
        symbol = trade["Symbol"]
        print (symbol)

def GetAccount(packageId,datetime1,datetime2):

    dates = []
    package_id_list = []
    csi300 = database.find("Index", "000300.SH_Time_86400_Bar", datetime1, datetime2)
    for i in range(len(csi300)):
        dates.append(csi300[i]["StdDateTime"])
    packageIds = packageId
    for package_id in packageIds:
        package_id_list.append({"Portfolio": package_id})

    filter = {"$or": package_id_list}
    accounts = database.find("Talent", "Account", datetime1, datetime2, query=filter)
    net_portfolio = []
    i = 0
    while i < len(dates):
        value_portfolio = 0
        j = 0
        for account in accounts:
            if account["StdDateTime"] == dates[i]:
                value_portfolio += account["Value"]
                j += 1
        if j < len(packageIds):
            value_portfolio += (len(packageIds)-1 - j ) * 100000000

        net_portfolio.append(value_portfolio)

        #print(value_portfolio)
        i = i + 1
    return net_portfolio[0]
def GetTalentList():
    #
    portfolios = database.find("Talent", "Portfolio", query={"Disabled": 0})
    #
    datetime1 = datetime.datetime(2017, 5, 1)
    datetime1 = Gadget.ToUTCDateTime(datetime1)
    datetime2 = datetime.datetime(2018, 6, 15)
    datetime2 = Gadget.ToUTCDateTime(datetime2)

    data = []
    packageId_all = []
    for p in portfolios:
        packageId_all.append (p["Name"])
    return packageId_all
def Sectors():
    a, b = IO.ReadCSVFile("D:\\股票所属行业表.csv")
    # print(stock_id['000001.SZ']['Name'])
    stock_name_sector = {}
    for i in range(len(b)):
        symbol = b[i][0]
        if symbol not in stock_name_sector:
            stock_name_sector[symbol] = {}
            stock_name_sector[symbol]['Symbol'] = b[i][0]
            stock_name_sector[symbol]['Name'] = b[i][1]
            stock_name_sector[symbol]['Sector'] = b[i][2]
    return stock_name_sector
def PositionAnalysis(packageIds):
    datetime1 = datetime.datetime(2018, 3, 11)
    print(datetime1)
    datetime1 = Gadget.ToUTCDateTime(datetime1)
    datetime2 = datetime.datetime(2018, 6, 15)
    print(datetime2)
    datetime2 = Gadget.ToUTCDateTime(datetime2)
    stock_sector = Sectors()
    csi300 = database.find("Index", "000300.SH_Time_86400_Bar", datetime1, datetime2)
    dates = []
    index = []
    net_in_beginning = GetAccount(packageIds,datetime1,datetime2)
    package_id_list = []
    for package_id in packageIds:
        package_id_list.append({"Portfolio": package_id})

    filter = {"$or": package_id_list}
    trades = database.find("Talent", "Trade", datetime1, datetime2, query=filter)
    positions = {}
    for i in range(len(csi300)):
        dates.append(csi300[i]["StdDateTime"])
        index.append(csi300[i]["Close"]/csi300[0]["Close"])
    i = 0
    j = 0
    while i < len(dates):
        for symbol in positions:
            quotes = database.find("Quote", symbol + "_Time_86400_Bar", dates[i] - datetime.timedelta(days=50),
                                   dates[i])
            quote = quotes[len(quotes) - 1]
            quote_lastday = quotes[len(quotes) - 2]
            positions[symbol]["AdjFactor"] = quote["AdjFactor"] / quote_lastday["AdjFactor"]
            positions[symbol]["Qty"] = positions[symbol]["Qty"] * positions[symbol]["AdjFactor"]

        while j < len(trades) and dates[i] >= trades[j]["StdDateTime"]:
            symbol = trades[j]["Symbol"]
            if symbol not in positions:
                doc = {}
                doc["Symbol"] = symbol
                doc["Qty"] = 0
                doc["Price"] = trades[j]["Price"]
                doc["CashFlow"] = 0
                doc["AdjFactor"] = 1
                doc["Sector"] = 0
                doc["Name"] = 0
                positions[symbol] = doc
            positions[symbol]["Qty"] = positions[symbol]["Qty"] + trades[j]["Qty"]
            positions[symbol]["CashFlow"] = positions[symbol]["CashFlow"] + trades[j]["CashFlow"]
            positions[symbol]["Sector"] = stock_sector[symbol]["Sector"]
            positions[symbol]["Name"] = stock_sector[symbol]["Name"]
            print(symbol,trades[j]["CashFlow"] )
            j = j + 1
        i = i + 1

    for symbol in positions:
        print (symbol, positions[symbol]["Name"], positions[symbol]["CashFlow"], - positions[symbol]["CashFlow"]/ net_in_beginning ,positions[symbol]["Sector"])


    positions_sector = {}
    for symbol in positions:
        sector = positions[symbol]["Sector"]
        if sector not in positions_sector:
            doc = {}
            doc["Sector"] = sector
            doc["CashFlow"] = 0
            positions_sector[sector] = doc
        positions_sector[sector]["CashFlow"] = positions_sector[sector]["CashFlow"] + positions[symbol]["CashFlow"]
    for sector in positions_sector:
        print(sector , positions_sector[sector]["CashFlow"] , -positions_sector[sector]["CashFlow"]/net_in_beginning)

from Core.Config import Config
config = Config()
database = config.DataBase()


kkwood = 0
packageId_16 = ["12126", "11303", "12230","11147","12340","12044","11354","11556","12495","11500","12279","11370","12308","11738","12334","12341"]
packageId_26 = ["12126","11303","12230","11147", "12340", "12044", "11354", "11556", "12495", "11500", "12279", "11370",
"12308","11738", "12334", "12341", "12304", "11313","12404", "12103","11175","11251","12419","11373","12036","12195"]
packageId_all = GetTalentList()
PositionAnalysis(packageId_16)

